<template>
    <div>
        <el-form label-width="100px" :model="spuInfo">
            <el-form-item label="sup名称">
                <el-input placeholder="spu名称" v-model="spuInfo.spuName"></el-input>
            </el-form-item>
            <el-form-item label="品牌">
                <el-select v-model="spuInfo.tmId" placeholder="请选择品牌">
                    <el-option :label="tm.tmName" :value="tm.id" v-for="(tm,index) in trademarkList" :key="tm.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input type="textarea" placeholder="spu描述" rows="4" v-model="spuInfo.description"></el-input>
            </el-form-item>
            <el-form-item label="SPU图片">
                <el-upload
                    action="/dev-api/admin/product/fileUpload"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :on-success="handlePictureSuccess"
                    :file-list="spuImageList">
                    <i class="el-icon-plus"></i>
                    </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
            </el-form-item>
            <el-form-item label="销售属性">
            <el-select v-model="saleAttrIdName" :placeholder="unSelectAttrList.length?`还有${unSelectAttrList.length}未选择`:'没有未选的'">
                <el-option :label="unSelectAttr.name" :value="`${unSelectAttr.id}:${unSelectAttr.name}`" v-for="(unSelectAttr, index) in unSelectAttrList" :key="unSelectAttr.id"></el-option>
            </el-select>
            <el-button type="primary" icon="el-icon-plus" :disabled="!saleAttrIdName" @click="addSaleAttr">添加销售属性</el-button>
            <el-table
                :data="spuInfo.spuSaleAttrList"
                border
                style="width: 100%">
                <el-table-column
                    type="index"
                    label="序号"
                    width="80">
                </el-table-column>
                <el-table-column
                    prop="saleAttrName"
                    label="属性名"
                    width="150">
                </el-table-column>
                <el-table-column
                    prop="prop"
                    label="属性值列表"
                    width="width">
                    <template slot-scope="{row,$index}">
                        <el-tag
                        v-for="(saleAttrValue,index) in row.spuSaleAttrValueList"
                        :key ="saleAttrValue.id"
                        closable
                        :disable-transitions="false"
                        @close="row.spuSaleAttrValueList.splice(index,1)"
                        >
                            {{saleAttrValue.saleAttrValueName}}
                        </el-tag>
                        <!--                         @keyup.enter.native="handleInputConfirm"
                        @blur="handleInputConfirm"
                        v-if="inputVisible"
                        v-model="inputValue"
                        -->
                        <el-input
                        v-if="row.isEdit"
                        class="input-new-tag"
                        ref="saveTagInput"
                        size="small"
                        v-model="row.saleAttrValueName"
                        @keyup.enter.native="handleInputConfirm(row)"
                        @blur="handleInputConfirm(row)"
                        >
                        </el-input>
                        <el-button v-else  class="button-new-tag" size="small" @click="showInput(row)">添加</el-button></el-button>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="prop"
                    label="操作"
                    width="150">
                    <template slot-scope="{row,$index}">
                        <HintButton title="删除" type="danger" icon="el-icon-delete" @click="spuInfo.spuSaleAttrList.splice($index,1)"/>
                    </template>
                </el-table-column>
            </el-table>
            </el-form-item>
            <el-form-item >
                <el-button type="primary" @click="save">保存</el-button>
                <el-button type="warning" @click='cancel'>取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
export default {
    name: 'spuForm',
    data() {
        return {
            category3Id:'',
            dialogImageUrl: '',
            dialogVisible: false,
            //表单收集的spu数据
            spuInfo : {
                category3Id:'',
                description:'',
                spuImageList:[],
                tmId:'',
                spuName:'',
                spuSaleAttrList:[]
            },
            spuImageList:[],//spu的图片列表
            baseSaleAttrList:[], //所有的销售属性列表
            trademarkList:[],
            saleAttrIdName:'',//未选择的销售属性
        };
    },
    methods: {
        //删除图片的回调函数
        handleRemove(file, fileList) {
            console.log(file, fileList);
            this.spuImageList = fileList
        },
        //预览大图的时候
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        //上传图片成功的回调，也是收集用户
        handlePictureSuccess(res,file,fileList){
            this.spuImageList = fileList
        },
        //请求获取添加spu的初始化动态数据
        async getAddSpuFormInitData(category3Id){
            //父组件传递过来的用于保存属性整理参数的值
            this.category3Id = category3Id
             //获取品牌列表
            const resultTrademark = await this.$API.trademark.getList()
            if(resultTrademark.code === 200 || resultTrademark.code === 20000){
                this.trademarkList = resultTrademark.data
            }
            //获取平台属性列表
            const attrResult = await this.$API.spu.getSaleAttrList()
            if(attrResult.code === 200 || attrResult.code === 20000){
                this.baseSaleAttrList = attrResult.data
            }
        },
        //请求获取修改spu的初始化动态数据
        async getUpdateSpuFormInitData(spu,category3Id){
        //父组件传递过来的用于保存属性整理参数的值
            this.category3Id = category3Id
            //获取spu详情
            const result = await this.$API.spu.get(spu.id)
            if(result.code === 200 || result.code === 20000){
                this.spuInfo = result.data
            }
            //根据spuId获取spu图片
            const resultImage = await this.$API.sku.getSpuImageList(spu.id)
            if(resultImage.code === 200 || resultImage.code === 20000){
                // const spuImageList = resultImage.data
                // spuImageList.map(item=>{
                //     item.name= item.imgName
                //     item.url = item.imgUrl
                // })
                // this.spuImageList = spuImageList
                resultImage.data.forEach(item=>{
                    item.name = item.imgName
                    item.url = item.imgUrl
                    // return item
                })
                this.spuImageList = resultImage.data
            }
            //获取品牌列表
            const resultTrademark = await this.$API.trademark.getList()
            if(resultTrademark.code === 200 || resultTrademark.code === 20000){
                this.trademarkList = resultTrademark.data
            }
            //获取平台属性列表
            const attrResult = await this.$API.spu.getSaleAttrList()
            if(attrResult.code === 200 || attrResult.code === 20000){
                this.baseSaleAttrList = attrResult.data
            }
        },
        //用户点击添加销售属性
        addSaleAttr(){
            let [baseSaleAttrId,saleAttrName] = this.saleAttrIdName.split(':')
            let obj ={
                baseSaleAttrId,
                saleAttrName,
                spuSaleAttrValueList:[]
            }
            this.spuInfo.spuSaleAttrList.push(obj)
            //清除选择的属性
            this.saleAttrIdName = ''
        },
        //点击添加销售属性值的列表
        showInput(row){
            // row.isEdit= true 变为响应式
            this.$set(row,'isEdit',true)
            this.$set(row,'saleAttrValueName','')
            this.$nextTick(()=>{
                this.$refs.saveTagInput.focus()
            })
        },
        //收集销售属性值的input
        handleInputConfirm(row){
            let {baseSaleAttrId,saleAttrValueName} = row
            if(saleAttrValueName.trim() === ''){
                // this.$message.error('属性值不能为空')
                row.isEdit = false
                return
            }
            //判断重复性
            let isRepeat =  row.spuSaleAttrValueList.some(item=> item.saleAttrValueName === saleAttrValueName.trim())
            if(isRepeat){
                this.$message.error('属性值不能重复')
                return
            }
            let obj ={
                baseSaleAttrId,
                saleAttrValueName
            }
            row.spuSaleAttrValueList.push(obj)
            //清除input内容
            row.saleAttrValueName=''
            row.isEdit = false
        },
        //点击保存按钮
        async save(){
            //获取参数 整理参数 发请求 成功干啥 失败干啥
            let {category3Id,spuInfo,spuImageList} = this
            spuInfo.category3Id = category3Id
            spuInfo.spuImageList = spuImageList.map(item => {
                return {
                    imgName:item.name,
                    imgUrl:item.imgUrl || item.response.data
                }
            })
            spuInfo.spuSaleAttrList.forEach(item => {
                delete item.isEdit
                delete item.saleAttrValueName
            })
            try {
                const result= await this.$API.spu.addUpdate(spuInfo)
                if(result.code === 200 || result.code === 20000){
                    this.$message.success('保存spu成功')
                    this.$emit('update:isShowSpuForm',false)
                    //返回父组件，通知父组件保存成功
                    this.$emit('backSuccess',spuInfo.id)
                    //切记data清空数据,组件不会立马销毁
                    this.resetData()

                }else {
                    this.$message.error('保存spu失败')
                }
            } catch (error) {
                this.$message.error('保存请求失败')
            }
        },
        //清空数据
        resetData(){
            //this.$option.data
            // Object.assign(this._data,this.$options.data())
            this.category3Id=''
            this.dialogImageUrl= ''
            this.dialogVisible= false
            //表单收集的spu数据
            this.spuInfo = {
                category3Id:'',
                description:'',
                spuImageList:[],
                tmId:'',
                spuName:'',
                spuSaleAttrList:[]
            }
            this.spuImageList=[]//spu的图片列表
            this.baseSaleAttrList=[] //所有的销售属性列表
            this.trademarkList=[]
        },
        //取消按钮返回
        cancel(){
            this.$emit('update:isShowSpuForm',false)
            // this.resetData()
            Object.assign(this._data,this.$options.data())
        }

    },
    computed:{
        //计算未选择的销售属性列表
        unSelectAttrList(){
            return this.baseSaleAttrList.filter(item=>{
                return this.spuInfo.spuSaleAttrList.every(item1=>{
                    return item1.saleAttrName !== item.name
                })
            })
        }
    }
}
</script>

<style>
    .el-tag + .el-tag {
        margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>
